package example.ble;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanFilter;
import android.bluetooth.le.ScanResult;
import android.bluetooth.le.ScanSettings;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.myapplication.R;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

public class MainActivity extends AppCompatActivity {

    private BluetoothAdapter mBluetoothAdapter;
    private List<ScanFilter> mScanFilterList = new ArrayList<>();
    private ScanSettings mScanSettings;
    private BluetoothLeScanner mBLEScanner;
    private boolean isScanning = false;
    private TableLayout table;

    private Map<BluetoothDevice, Integer> mDevList = new HashMap<>();
    private byte[] moveSpeed = new byte[2];
    private BluetoothGatt mGatt;

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private ScanCallback  mScanCallback = new ScanCallback() {
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            BluetoothDevice dev = result.getDevice();
            if(dev == null) {
                return;
            }
            String macAddr = dev.getAddress();
            for (BluetoothDevice d: mDevList.keySet()) {
                if(d.getAddress().equals(macAddr)) {
                    return;
                }
            }
            if(dev.getName() != null) {
                mDevList.put(dev, result.getRssi());
                updateToUI();
            }
        }
    };

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private void updateToUI() {

        table.removeAllViews();

        for (final BluetoothDevice dev: mDevList.keySet()) {

            TableRow row = new TableRow(this);

            TextView nameTv = new TextView(this);
            TextView macTv = new TextView(this);
            Button btnConn = new Button(this);

            nameTv.setText(dev.getName());
            macTv.setText(dev.getAddress());
            btnConn.setText("连接");

            row.addView(nameTv);
            row.addView(macTv);
            row.addView(btnConn);

            table.addView(row);

            btnConn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    connectToDevice(dev);
                }
            });
        }
    }

    private BluetoothGattCallback  mGattCallBack = new BluetoothGattCallback() {
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            if(newState == BluetoothProfile.STATE_CONNECTED) {
                mGatt.discoverServices();
            } else if(newState == BluetoothProfile.STATE_DISCONNECTED) {
                if(mGatt!= null) {
                    mGatt.close();
                }
            }
        }

        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
            if(characteristic.getUuid().toString().equals(CHAR_MOVE_UUID)) {
                moveSpeed = characteristic.getValue();
                //TODO应用到UI
            }
        }

        private final static String SERVICE_UUID =   "0000ffe0-0000-1000-8000-00805f9b34fb";
        private final static String CHAR_MOVE_UUID = "0000ffe1-0000-1000-8000-00805f9b34fb";
        private BluetoothGattCharacteristic  mCharMove;

        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            if(status == BluetoothGatt.GATT_SUCCESS) {
                List<BluetoothGattService> serviceList = gatt.getServices();
                for (BluetoothGattService service: serviceList) {
                    if(service.getUuid().toString().equals(SERVICE_UUID)) {
                        mCharMove = service.getCharacteristic(UUID.fromString(CHAR_MOVE_UUID));
                        final boolean result = gatt.setCharacteristicNotification(mCharMove, true);

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if(result) {
                                    Toast.makeText(MainActivity.this,"char move notify 开启成功", Toast.LENGTH_LONG).show();
                                } else {
                                    Toast.makeText(MainActivity.this,"char move notify 开启失败", Toast.LENGTH_LONG).show();
                                }
                            }
                        });
                    }
                }
            }
        }
    };
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private void connectToDevice(BluetoothDevice dev) {
        if(mGatt != null) {
            mGatt.close();
            mGatt = null;
        }
        if(isScanning) {
            scanBLEDevice(false);
        }
        mGatt = dev.connectGatt(this, false, mGattCallBack );
    }

    static final String[] PERMISSIONS = new String[] {
            Manifest.permission.BLUETOOTH,
            Manifest.permission.BLUETOOTH_SCAN,
            Manifest.permission.BLUETOOTH_CONNECT,
            Manifest.permission.BLUETOOTH_ADMIN,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION
    };

    private boolean hasPermission() {
        for (String p: PERMISSIONS) {
            int result = ContextCompat.checkSelfPermission(this, p);
            if(result != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if( !hasPermission() ) {
            ActivityCompat.requestPermissions(this, PERMISSIONS, 0);
        }

        setContentView(R.layout.activity_main);

        BluetoothManager manager = (BluetoothManager)getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = manager.getAdapter();

        ScanFilter filter = new ScanFilter.Builder().build();
        mScanFilterList.add(filter);
        mScanSettings = new ScanSettings.Builder().build();

        table = findViewById(R.id.tab_view);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onResume() {
        super.onResume();
        if(mBluetoothAdapter != null) {
            if(mBluetoothAdapter.isEnabled()) {
                mBLEScanner = mBluetoothAdapter.getBluetoothLeScanner();
                //开始扫描蓝牙设备
                scanBLEDevice(true);
            } else {
                Toast.makeText(this,"请开启蓝牙", Toast.LENGTH_LONG).show();
                //finish();
            }
        } else {
            //finish();
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private void scanBLEDevice(boolean enable) {
        if(mBLEScanner != null) {
            if(enable) {
                mBLEScanner.startScan(mScanFilterList, mScanSettings, mScanCallback);
            } else {
                mBLEScanner.stopScan(mScanCallback);
            }
            isScanning = enable;
            mDevList.clear();
        }
    }
}
